package com.ouyunc.oauth2.config.override;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.*;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidScopeException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.Set;
import java.util.UUID;

/**
 * @Author fangzhenxun
 * @Description 自定义tokenServices, 主要为了解决刷新token的时候使用自定义的UserDetailServices
 * 复制DefaultTokenServices中的代码，然后重写refreshAccessToken()，配置里面的详情信息
 * @Date 2020/4/22 14:21
 **/
public class ITokenServices implements AuthorizationServerTokenServices, ResourceServerTokenServices, ConsumerTokenServices, InitializingBean {

    // default 30 days.
    private int refreshTokenValiditySeconds = 60 * 60 * 24 * 30;

    // default 12 hours.
    private int accessTokenValiditySeconds = 60 * 60 * 12;

    private boolean supportRefreshToken = false;

    private boolean reuseRefreshToken = true;

    /**
     * 这里直接给他指定是IRedisTokenStore
     **/
    private IRedisTokenStore tokenStore;

    private ClientDetailsService clientDetailsService;

    private TokenEnhancer accessTokenEnhancer;

    private AuthenticationManager authenticationManager;

    /**
     * Initialize these token services. If no random generator is set, one will be created.
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(tokenStore, "tokenStore must be set");
    }



    /**
     * @Author fangzhenxun
     * @Description  创建token存在以下几种情况，建立在（refresh_token 的有效期时间比access_token的有效期时间长）：
     * 默认情况下，在access_token有效期内，第一次获取的一套相关token和第n次获取的token是同一套token（包括有效时间都一样）；
     *            如果在此期间刷新token，那么将会生成一套新的token（有效期时间也将重新计时），原来的（老的）token将失效
     * 其实最终我们可能在生产中用到这几种情况：
     * （1） 同一个可以对应多套有效的token ===》用户每次登陆（调用生成token接口）都会生成一套有效的token，这些套token互不影响（使用那一套都可以正常使用），不要混着用，比不用这一套的access_token和另外一套的refresh_token混淆着
     * （2） 同一个用户只对应一套有效的token ===》，这种情况有存在两种情况：
     *      （2.1）不允许异地登陆（也就是同一时间只能有一个用户在线登陆，当然也可以根据设备类型进行灵活配置：1，比如同一个用户可以在pc端和移动端同时登陆互不影响，但是每个相同的设备端只能允许一个用户在线登录； 2，比如同一个用户在pc端和移动端同时登陆只能有一个端登录），这个时候每次生成新的token的时候都会把原来老的那一套token给移除；
     *      （2.2）允许异地登录，存在两种情况（目前程序中默认是这一种）：
     *            （2.2.1）在access_token有效期内，用户第一次登陆和第n次登陆生成的token都是同一套（有效时间也是第一次登陆时的有效时间），但是在此期间如果调用刷新token，会生成一套新的token，原来的token将失效，当然可以配置是否重复使用refresh_token来决定是否重复使用第一次生成的refresh_token（如果使用则它的有效期时间一直是第一次的有效期时间）用于以后的刷新； 注意：这种情况可能造成，在同一个账号下你刷新他们失效，他们刷新你失效，这个时候只有他们重新登录重新获取上次刷新生成的有效token
     *            （2.2.1）当access_token过期，refresh_token没有过期时候，此时该用户的其他登录都失效了，这个时候会出现两种情况：
     *                  （2.2.1.1）同一个账号的某个用户再次登录（不通过刷新），那么会生成一套新的有效token（此时原来的refresh_token还是有效，可以继续用它来刷新获取token）， 如果在这个时候同一账号的其他登录者使用老的refresh_token来进行刷新，TODO 会得到一套新的有效token（有效期时间都会重新计时，包括refresh_token）,这样就不符合一个账户只有一套有效token了
     *                  （2.2.1.2）同一个账号的某个用户通过刷新，生成一套新的有效token（有效时间重新计时，老的刷新token被覆盖，失效了），这个时候如果同一账号的其他用户重新登录，则会重新获取刷新生成的新token，TODO 而如果同一账户的其他用户也使用老的refresh_token刷新，会惊讶的发现明明在有效期的refresh_token失效了（其实是根据你配置是否重复使用刷新token的策略来绝决定是否失效的），也可以配置不失效，但是当你配置原来的refresh_token重复使用时，他们再次使用老的refresh_token来刷新的时候，那么其他已经刷新所获得的的有效token将会被覆盖，进而失效；如果他们再次刷新这样就造成循环问题了
     * @Date 2020/7/9 9:00
     * @param authentication
     * @return org.springframework.security.oauth2.common.OAuth2AccessToken
     **/
    @Override
    @Transactional
    public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {

        //获取用户所对应的客户端信息，为了解决多次重复登录过期时间需要每次都是最新生成的有效时间
        ClientDetails clientDetails = getClientDetails(authentication.getOAuth2Request());
        Integer accessTokenValiditySeconds = clientDetails.getAccessTokenValiditySeconds();
        Integer refreshTokenValiditySeconds = clientDetails.getRefreshTokenValiditySeconds();

        OAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(authentication);

        OAuth2RefreshToken refreshToken = null;
        if (existingAccessToken != null) {
            //如果之前登录并且存在token，则只需更新token的有效期即可, 默认OAuth2AccessToken只有一个实现就是DefaultOAuth2AccessToken
            //重新设置access_token的过期时间
            ((DefaultOAuth2AccessToken)existingAccessToken).setExpiration(new Date(System.currentTimeMillis() + (accessTokenValiditySeconds * 1000L)));
            //重新设置refresh_token的过期时间
            ((DefaultOAuth2AccessToken) existingAccessToken).setRefreshToken(new DefaultExpiringOAuth2RefreshToken(existingAccessToken.getRefreshToken().getValue(), new Date(System.currentTimeMillis() + (refreshTokenValiditySeconds * 1000L))));

            //注意：todo 可以继续扩张根据用户类型（token在redis中的存储键前缀判断是否允许异地登陆）
            String userType = tokenStore.getPrefix();
            //如果想上面（2.1）实现不允许异地登陆的逻辑， 那么如果存在原有token则直接去掉下面的existingAccessToken.isExpired()判断直接删除原有token
            if (existingAccessToken.isExpired()) {
                if (existingAccessToken.getRefreshToken() != null) {
                    refreshToken = existingAccessToken.getRefreshToken();
                    // The token store could remove the refresh token when the
                    // access token is removed, but we want to
                    // be sure...
                    tokenStore.removeRefreshToken(refreshToken);
                }
                tokenStore.removeAccessToken(existingAccessToken);
            }
            else {
                // Re-store the access token in case the authentication has changed
                tokenStore.storeAccessToken(existingAccessToken, authentication);
                return existingAccessToken;
            }
        } else {
            //如果access_token过期，refresh_token 没有过期/或者已经过期，这个时候调用生成token 的接口的时候会有问题，将导致同一个账号多套有效token，该处理逻辑进行将refresh_token相关token删除，这些刷新相关token有可能不存在（比如第一次生成token，或者refresh_token也过期了）
            tokenStore.removeRefreshTokenWhenAccessTokenExpire(authentication);
        }

        // Only create a new refresh token if there wasn't an existing one
        // associated with an expired access token.
        // Clients might be holding existing refresh tokens, so we re-use it in
        // the case that the old access token
        // expired.
        if (refreshToken == null) {
            refreshToken = createRefreshToken(authentication);
        }
        // But the refresh token itself might need to be re-issued if it has
        // expired.
        else if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
            ExpiringOAuth2RefreshToken expiring = (ExpiringOAuth2RefreshToken) refreshToken;
            if (System.currentTimeMillis() > expiring.getExpiration().getTime()) {
                refreshToken = createRefreshToken(authentication);
            }
        }

        OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
        tokenStore.storeAccessToken(accessToken, authentication);
        // In case it was modified
        refreshToken = accessToken.getRefreshToken();
        if (refreshToken != null) {
            tokenStore.storeRefreshToken(refreshToken, authentication);
        }
        return accessToken;

    }

    /**
     * @Author fangzhenxun
     * @Description  主要针对刷新token的时候，用来获取以及添加额外的信息
     * @Date 2020/4/22 14:42
     * @param refreshTokenValue
     * @param tokenRequest
     * @return org.springframework.security.oauth2.common.OAuth2AccessToken
     **/
    @Override
    @Transactional(noRollbackFor={InvalidTokenException.class, InvalidGrantException.class})
    public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest) throws AuthenticationException {

        if (!supportRefreshToken) {
            throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
        }

        OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(refreshTokenValue);
        if (refreshToken == null) {
            throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
        }

        OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(refreshToken);

        //=============================================这里是需要复写的主要地方(可以定义序列化到redis的结构值)============================================
        if (this.authenticationManager != null && !authentication.isClientOnly()) {
            // The client has already been authenticated, but the user authentication might be old now, so give it a
            // chance to re-authenticate.

            //@todo 在获取Token的时候，像client_id,client_secret等请求参数，框架会自动放到details中，但是在刷新token的时候不知什么原因，details中并没有放入请求的参数，所以需要自己重新构造，还好这些信息都保存在tokenRequest中，所以new一个UsernamePasswordAuthenticationToken，把它们都放进details中，再传入
            //PreAuthenticatedAuthenticationToken，后续就交由框架去验证就可以了

            //由于自定义UserDetailsService,导致OAuth2Authentication 中的 Authentication userAuthentication 丢失了 Detail的信息,需要补上
            // 1.从tokenRequest中获取请求的信息,并重新构造成 UsernamePasswordAuthenticationToken
            // 2.设置好了Detail的信息再传入构造 PreAuthenticatedAuthenticationToken 交由后面的验证

            Object details = tokenRequest.getRequestParameters();

            Authentication atc = authentication.getUserAuthentication();
            //判断atc属于那种类型，然后将detail设置值，提供下在其他地方使用
            if (atc instanceof UsernamePasswordAuthenticationToken) {
                UsernamePasswordAuthenticationToken userAuthentication = (UsernamePasswordAuthenticationToken) atc;
                userAuthentication.setDetails(details);
            }
            if (atc instanceof PreAuthenticatedAuthenticationToken) {
                PreAuthenticatedAuthenticationToken pre = (PreAuthenticatedAuthenticationToken) atc;
                pre.setDetails(details);
            }

            //去掉原来的,使用自己重新构造的 userAuthentication
            PreAuthenticatedAuthenticationToken preAuthenticatedAuthentication = new PreAuthenticatedAuthenticationToken(atc, "", authentication.getAuthorities());
            preAuthenticatedAuthentication.setDetails(details);

            //直接设置details,方便在wrapper中拿到
            Authentication user = this.authenticationManager.authenticate(preAuthenticatedAuthentication);
            authentication = new OAuth2Authentication(authentication.getOAuth2Request(), user);
            authentication.setDetails(details);

        }

        String clientId = authentication.getOAuth2Request().getClientId();
        if (clientId == null || !clientId.equals(tokenRequest.getClientId())) {
            throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue);
        }

        // clear out any access tokens already associated with the refresh
        // token.
        //清除和该refresh_token 已经绑定的access_token
        tokenStore.removeAccessTokenUsingRefreshToken(refreshToken);

        if (isExpired(refreshToken)) {
            tokenStore.removeRefreshToken(refreshToken);
            throw new InvalidTokenException("Invalid refresh token (expired): " + refreshToken);
        }

        authentication = createRefreshedAuthentication(authentication, tokenRequest);

        if (!reuseRefreshToken) {
            tokenStore.removeRefreshToken(refreshToken);
            refreshToken = createRefreshToken(authentication);
        }

        OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
        tokenStore.storeAccessToken(accessToken, authentication);
        if (!reuseRefreshToken) {
            tokenStore.storeRefreshToken(accessToken.getRefreshToken(), authentication);
        }
        return accessToken;
    }

    @Override
    public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
        return tokenStore.getAccessToken(authentication);
    }

    /**
     * Create a refreshed authentication.
     *
     * @param authentication The authentication.
     * @param request The scope for the refreshed token.
     * @return The refreshed authentication.
     * @throws InvalidScopeException If the scope requested is invalid or wider than the original scope.
     */
    private OAuth2Authentication createRefreshedAuthentication(OAuth2Authentication authentication, TokenRequest request) {
        OAuth2Authentication narrowed = authentication;
        Set<String> scope = request.getScope();
        OAuth2Request clientAuth = authentication.getOAuth2Request().refresh(request);
        if (scope != null && !scope.isEmpty()) {
            Set<String> originalScope = clientAuth.getScope();
            if (originalScope == null || !originalScope.containsAll(scope)) {
                throw new InvalidScopeException("Unable to narrow the scope of the client authentication to " + scope
                        + ".", originalScope);
            }
            else {
                clientAuth = clientAuth.narrowScope(scope);
            }
        }
        narrowed = new OAuth2Authentication(clientAuth, authentication.getUserAuthentication());
        return narrowed;
    }

    protected boolean isExpired(OAuth2RefreshToken refreshToken) {
        if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
            ExpiringOAuth2RefreshToken expiringToken = (ExpiringOAuth2RefreshToken) refreshToken;
            return expiringToken.getExpiration() == null
                    || System.currentTimeMillis() > expiringToken.getExpiration().getTime();
        }
        return false;
    }

    @Override
    public OAuth2AccessToken readAccessToken(String accessToken) {
        return tokenStore.readAccessToken(accessToken);
    }

    @Override
    public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException,
            InvalidTokenException {
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue);
        if (accessToken == null) {
            throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
        }
        else if (accessToken.isExpired()) {
            tokenStore.removeAccessToken(accessToken);
            throw new InvalidTokenException("Access token expired: " + accessTokenValue);
        }

        OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
        if (result == null) {
            // in case of race condition
            throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
        }
        if (clientDetailsService != null) {
            String clientId = result.getOAuth2Request().getClientId();
            try {
                clientDetailsService.loadClientByClientId(clientId);
            }
            catch (ClientRegistrationException e) {
                throw new InvalidTokenException("Client not valid: " + clientId, e);
            }
        }
        return result;
    }

    public String getClientId(String tokenValue) {
        OAuth2Authentication authentication = tokenStore.readAuthentication(tokenValue);
        if (authentication == null) {
            throw new InvalidTokenException("Invalid access token: " + tokenValue);
        }
        OAuth2Request clientAuth = authentication.getOAuth2Request();
        if (clientAuth == null) {
            throw new InvalidTokenException("Invalid access token (no client id): " + tokenValue);
        }
        return clientAuth.getClientId();
    }

    @Override
    public boolean revokeToken(String tokenValue) {
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
        if (accessToken == null) {
            return false;
        }
        if (accessToken.getRefreshToken() != null) {
            tokenStore.removeRefreshToken(accessToken.getRefreshToken());
        }
        tokenStore.removeAccessToken(accessToken);
        return true;
    }

    private OAuth2RefreshToken createRefreshToken(OAuth2Authentication authentication) {
        if (!isSupportRefreshToken(authentication.getOAuth2Request())) {
            return null;
        }
        int validitySeconds = getRefreshTokenValiditySeconds(authentication.getOAuth2Request());
        String value = UUID.randomUUID().toString();
        if (validitySeconds > 0) {
            return new DefaultExpiringOAuth2RefreshToken(value, new Date(System.currentTimeMillis()
                    + (validitySeconds * 1000L)));
        }
        return new DefaultOAuth2RefreshToken(value);
    }

    private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) {
        DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString());
        int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request());
        if (validitySeconds > 0) {
            token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
        }
        token.setRefreshToken(refreshToken);
        token.setScope(authentication.getOAuth2Request().getScope());

        return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token;
    }

    /**
     * The access token validity period in seconds
     *
     * @param clientAuth the current authorization request
     * @return the access token validity period in seconds
     */
    protected int getAccessTokenValiditySeconds(OAuth2Request clientAuth) {
        if (clientDetailsService != null) {
            ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
            Integer validity = client.getAccessTokenValiditySeconds();
            if (validity != null) {
                return validity;
            }
        }
        return accessTokenValiditySeconds;
    }

  /**
   * @Author fangzhenxun
   * @Description  自定义一个方法，通过OAuth2Request 请求获取客户端信息
   * @Date 2020/7/9 14:00
   * @param clientAuth
   * @return org.springframework.security.oauth2.provider.ClientDetails
   **/
    protected ClientDetails getClientDetails(OAuth2Request clientAuth) {
        ClientDetails client = null;
        if (clientDetailsService != null) {
            client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
        }
        return client;
    }

    /**
     * The refresh token validity period in seconds
     *
     * @param clientAuth the current authorization request
     * @return the refresh token validity period in seconds
     */
    protected int getRefreshTokenValiditySeconds(OAuth2Request clientAuth) {
        if (clientDetailsService != null) {
            ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
            Integer validity = client.getRefreshTokenValiditySeconds();
            if (validity != null) {
                return validity;
            }
        }
        return refreshTokenValiditySeconds;
    }

    /**
     * Is a refresh token supported for this client (or the global setting if
     * {@link #setClientDetailsService(ClientDetailsService) clientDetailsService} is not set.
     *
     * @param clientAuth the current authorization request
     * @return boolean to indicate if refresh token is supported
     */
    protected boolean isSupportRefreshToken(OAuth2Request clientAuth) {
        if (clientDetailsService != null) {
            ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
            return client.getAuthorizedGrantTypes().contains("refresh_token");
        }
        return this.supportRefreshToken;
    }

    /**
     * An access token enhancer that will be applied to a new token before it is saved in the token store.
     *
     * @param accessTokenEnhancer the access token enhancer to set
     */
    public void setTokenEnhancer(TokenEnhancer accessTokenEnhancer) {
        this.accessTokenEnhancer = accessTokenEnhancer;
    }

    /**
     * The validity (in seconds) of the refresh token. If less than or equal to zero then the tokens will be
     * non-expiring.
     *
     * @param refreshTokenValiditySeconds The validity (in seconds) of the refresh token.
     */
    public void setRefreshTokenValiditySeconds(int refreshTokenValiditySeconds) {
        this.refreshTokenValiditySeconds = refreshTokenValiditySeconds;
    }

    /**
     * The default validity (in seconds) of the access token. Zero or negative for non-expiring tokens. If a client
     * details service is set the validity period will be read from the client, defaulting to this value if not defined
     * by the client.
     *
     * @param accessTokenValiditySeconds The validity (in seconds) of the access token.
     */
    public void setAccessTokenValiditySeconds(int accessTokenValiditySeconds) {
        this.accessTokenValiditySeconds = accessTokenValiditySeconds;
    }

    /**
     * Whether to support the refresh token.
     *
     * @param supportRefreshToken Whether to support the refresh token.
     */
    public void setSupportRefreshToken(boolean supportRefreshToken) {
        this.supportRefreshToken = supportRefreshToken;
    }

    /**
     * Whether to reuse refresh tokens (until expired).
     *
     * @param reuseRefreshToken Whether to reuse refresh tokens (until expired).
     */
    public void setReuseRefreshToken(boolean reuseRefreshToken) {
        this.reuseRefreshToken = reuseRefreshToken;
    }

    /**
     * The persistence strategy for token storage.
     *
     * @param tokenStore the store for access and refresh tokens.
     */
    public void setTokenStore(IRedisTokenStore tokenStore) {
        this.tokenStore = tokenStore;
    }

    /**
     * An authentication manager that will be used (if provided) to check the user authentication when a token is
     * refreshed.
     *
     * @param authenticationManager the authenticationManager to set
     */
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    /**
     * The client details service to use for looking up clients (if necessary). Optional if the access token expiry is
     * set globally via {@link #setAccessTokenValiditySeconds(int)}.
     *
     * @param clientDetailsService the client details service
     */
    public void setClientDetailsService(ClientDetailsService clientDetailsService) {
        this.clientDetailsService = clientDetailsService;
    }

}
